package com.ccl.keyassistant.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.ClipboardManager;
import android.text.InputType;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ccl.keyassistant.MainActivity;
import com.ccl.keyassistant.R;
import com.ccl.keyassistant.adapter.KeyRecyclerAdapter;
import com.ccl.keyassistant.db.DBDataHelper;
import com.ccl.keyassistant.db.DBHelper;
import com.ccl.keyassistant.entity.BaseModel;
import com.ccl.keyassistant.entity.KeyItem;
import com.ccl.keyassistant.entity.KeyModel;
import com.ccl.keyassistant.utils.L;
import com.ccl.keyassistant.utils.StaticClass;
import com.ccl.keyassistant.view.CustomDialog;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;


public class KeyFragment extends Fragment implements View.OnClickListener , MainActivity.OnSearchCommittedListener {

    private View mKeyFragment;
    private RecyclerView mRecyclerView;
    private List<KeyItem> mData = new ArrayList<>();
    private KeyRecyclerAdapter adapter;
    private TextView mFileName;
    private Button mBtnOk;
    private TextView mPass;
    private TextView mRemark;
    private Button mBtnShow;
    private TextView mTime;
    private boolean currPassState = false;
    private CustomDialog dialog_show_item;
    private TextView mCopy;
    private TextView mDele;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mKeyFragment = inflater.inflate(R.layout.fragment_key, container, false);

        new KeyAsyncTask().execute("");
        initView();

        return mKeyFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        L.i("key frag");
        new KeyAsyncTask().execute("");
//        getData(null);
//        if (adapter != null) {
//            adapter.notifyDataSetChanged();
//        }
    }



    public void search(String se) {
//        getData(se);
//        adapter.notifyDataSetChanged();
        new KeyAsyncTask().execute(se);
    }

    /**
     * search ==null // ""查询所有
     *
     * @param search
     */
    private void getData(String search) {
        //从数据库中查询数据
        DBDataHelper dataHelper = DBDataHelper.getInstance(getContext());
        ArrayList<BaseModel> select = null;
        if (search == null || "".equals(search)) {
            //查询
            select = dataHelper.select(DBHelper.TABLE_KEY, new String[]{
                    DBHelper.FILENAME, DBHelper.PASSWORD, DBHelper.REMARK, DBHelper.TIME
            }, null, null, null, KeyModel.class);
        } else {
            String selection = DBHelper.FILENAME + " like ?";
            select = dataHelper.select(DBHelper.TABLE_KEY, new String[]{
                    DBHelper.FILENAME, DBHelper.PASSWORD, DBHelper.REMARK, DBHelper.TIME
            }, selection, new String[]{"%" + search + "%"}, null, KeyModel.class);
        }
        mData.clear();
        for (BaseModel model : select) {
            KeyModel key = (KeyModel) model;
            KeyItem keyItem = new KeyItem(key.file_name, key.remark, key.password, key.create_time);
            mData.add(keyItem);
        }
//        if(adapter!=null){
//            adapter.notifyDataSetChanged();
//        }
    }

    private void initView() {


        mRecyclerView = (RecyclerView) mKeyFragment.findViewById(R.id.key_recycle);

        adapter = new KeyRecyclerAdapter(getContext(), mData);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mRecyclerView.setAdapter(adapter);


        adapter.setOnItemClickListener(new KeyRecyclerAdapter.OnItemClickListener() {
            @Override
            public void itemClick(final int poistion) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog_show_item = initDialog();
                        KeyItem keyItem = mData.get(poistion);
                        mFileName.setText(keyItem.getKeyname());
                        mRemark.setText(keyItem.getRemark());
                        mTime.setText(keyItem.getTime());
                        mPass.setText(keyItem.getPassword());
                        dialog_show_item.show();
                    }
                });
            }
        });

        ((MainActivity)getActivity()).SetOnSearchCommittedListener(this);
    }

    private CustomDialog initDialog() {
        CustomDialog showDialog = new CustomDialog(getContext(), R.layout.show_key_dialog);
        Window window = showDialog.getWindow();
        mFileName = window.findViewById(R.id.show_key_filename);
        mBtnOk = window.findViewById(R.id.show_key_ok);
        mPass = window.findViewById(R.id.show_key_pass);
        mRemark = window.findViewById(R.id.show_key_remark);
        mBtnShow = window.findViewById(R.id.show_key_show);
        mTime = window.findViewById(R.id.show_key_time);
        mCopy = window.findViewById(R.id.show_key_copy);
        mDele = window.findViewById(R.id.show_key_delete);

        mBtnOk.setOnClickListener(this);
        mBtnShow.setOnClickListener(this);
        mCopy.setOnClickListener(this);
        mDele.setOnClickListener(this);
        return showDialog;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_key_ok:
                if (dialog_show_item != null) {
                    dialog_show_item.dismiss();
                }
                currPassState = false;
                break;
            case R.id.show_key_show:
                if (!currPassState) {
                    //显示密码
                    mPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //隐藏密码
                    mPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                currPassState = !currPassState;
                break;
            case R.id.show_key_copy:
                //实现复制密码
                ClipboardManager manager = (ClipboardManager) getActivity().
                        getSystemService(Context.CLIPBOARD_SERVICE);

                manager.setText(mPass.getText().toString());
                Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.show_key_delete:
                AlertDialog.Builder delete = new AlertDialog.Builder(getContext(),R.style.AppCompatAlertDialogStyle);
                delete.setTitle("警告");
                delete.setMessage("是否删除");
                delete.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                delete.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除密钥
                        Executors.newSingleThreadExecutor().submit(new Runnable() {
                            @Override
                            public void run() {
                                DBDataHelper helper = DBDataHelper.getInstance(getContext());
                                String whereCase = DBHelper.FILENAME+" =? and "+DBHelper.PASSWORD+" =? ";
                                helper.delete(DBHelper.TABLE_KEY,whereCase,new String[]{
                                        mFileName.getText().toString(),mPass.getText().toString()
                                });
                            }
                        });

                        Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                        if(dialog_show_item!=null){
                            dialog_show_item.dismiss();
                            new KeyAsyncTask().execute("");
                        }
                        dialog.dismiss();

                    }
                });
                delete.create().show();

                break;
            default:
                break;
        }
    }

    class KeyAsyncTask extends AsyncTask<String,Void,Void>{

        @Override
        protected Void doInBackground(String... strings) {
            getData(strings[0]);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if(adapter!=null){
                adapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void searchCommitted(String str) {
        search(str);
    }

    @Override
    public void searchClose(String str) {
        search(str);
    }
}
